package google.news;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import proxy.HttpProxy;
import proxy.Proxy;

import java.io.IOException;

/**
 * Created by zhongwei on 2017/1/28.
 */
public class HttpDownLoader {

    private HttpProxy proxy;

    public String download(String url) {
        if (proxy == null) {
            changeProxy(url);
        }
        try {
            Document document = Jsoup.connect(url).validateTLSCertificates(false).userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36").header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4").proxy(proxy.getHost(), proxy.getPort()).timeout(6000).get();
            return document.html();
        } catch (Exception ex) {
            changeProxy(url);
            return download(url);
        }
    }

    public String download(String url, String localProxy) {
        if (proxy == null) {
            changeProxyLocal(url);
        }
        try {
            Document document = Jsoup.connect(url).validateTLSCertificates(false).userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36").header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4").proxy(proxy.getHost(), proxy.getPort()).timeout(10000).get();
            return document.html();
        } catch (IOException ex) {
            changeProxyLocal(url);
            return download(url);
        }
    }

    private void changeProxy(String url) {
        try {
            String proxyStr = Proxy.getProxy();
            String[] arr = proxyStr.split(":");
            String host = arr[0];
            int port = Integer.parseInt(arr[1]);
            proxy = new HttpProxy(host, port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void changeProxyLocal(String url) {
        try {
            String proxyStr = Proxy.getLocalProxy();
            String[] arr = proxyStr.split(":");
            String host = arr[0];
            int port = Integer.parseInt(arr[1]);
            proxy = new HttpProxy(host, port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
